/**
 * 详情对话框
 */
var StoragePutSingleInfoDlg = {
    data: {
    	positionNumber: "",
    }
};
/**
 * 添加或者修改页面
 */
var OrderPutDetailedInfoDlg = {
    data: {
        detailedGoodsname: "",
        detailedGoodsnum: "",
        goodsNumber: "",
		goodsNo:"",
        detailedRebubbles: "",
        detailedPacking: "",
        detailedLargeclass: "",
        detailedGoodstype: "",
        detailedPutcondition: "",
        detailedPiecenum: "",
        goodsWeight: "",
        goodsVolume: "",
    }
};

var inputlist = []
var submit = 2
layui.use(['table', 'admin', 'ax','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var form = layui.form;
    
    laydate.render({
    	elem:'#startPutTime'
    });
    
    laydate.render({
    	elem:'#endPutTime'
    });
    
    laydate.render({
    	elem:'#startSingleTime'
    });
    
    laydate.render({
    	elem:'#endSinglePutTime'
    });

    /**
     * 库存表管理
     */
    var StorageStock = {
        tableId: "storageStockTable"
    };

    /**
     * 初始化表格的列
     */
    StorageStock.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {field: 'stockstate', title: 'Status',templet: '#stockstateTpl'},
            {field: 'operateName', title: 'Project'},
            {field: 'customerName', title: 'Customer'},
            {field: 'warehouseName', title: 'Warehouse'},
            {field: 'areaNumber', title: 'Area'},
            {field: 'positionNumber', title: 'Location', style:'background-color: #ecf5ff;font-weight: 600;' , sort: true},
            {field: 'trayNumber', title: 'Tray No' , sort: true},
            {field: 'goodsName', title: 'Product', style:'background-color: #dbf1e1;font-weight: 600;', width:270},
            {field: 'goodsNumber', title: 'Product No', sort: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNo', title: 'SKU', sort: true, style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: 'Total:'},
            {field: 'num', title: 'Quantity', sort: true, style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            /*{field: 'storageNumber', title: 'Pending Picking Qty', totalRow: true},*/
            {field: 'putTime', title: 'Receipt Batch' , sort: true},
            {field: 'producetime', title: 'Production Date'},
            {field: 'goodsbatchs', title: 'Batch'},
            {field: 'stockWeight', title: 'Weight', totalRow: true},
            {field: 'stockVolume', title: 'Volume', totalRow: true},
            {field: 'stockMoney', title: 'Amount', totalRow: true},
            {field: 'unitprice', title: 'Unit Price'},
            {field: 'goodsBigtype', title: 'Category'},
            {field: 'goodsType', title: 'Type', hide: true},
            {field: 'goodsUnit', title: 'Unit'},
            {field: 'goodsPacking', title: 'Packing'},
            {field: 'goodsSpecs', title: 'Specs'},
            {field: 'goodsWarranty', title: 'Warranty(days)'},
            {field: 'createTime', title: 'Create Time'},
            {field: 'updateTime', title: 'Update Time'},
            {fixed: 'right',align: 'center', toolbar: '#tableBar', title: 'Action'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    StorageStock.search = function () {
        var queryData = {};
        queryData['stockstate'] = $("#stockstate").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['warehouseId'] = $("#warehouseId").val();
        queryData['areaId'] = $("#areaId").val();
        queryData['positionNumber'] = $("#positionNumber").val();
        queryData['goodsNumber'] = $("#goodsNumber").val();
        queryData['goodsName'] = $("#goodsName").val();
        queryData['goodsNo'] = $("#goodsNo").val();
        queryData['goodsbatchs'] = $("#goodsbatchs").val();//批次
        queryData['startPutTime'] = $("#startPutTime").val();//入库时间
        queryData['endPutTime'] = $("#endPutTime").val();//入库时间截止
        queryData['startSingleTime'] = $("#startSingleTime").val();//生产日期
        queryData['endSinglePutTime'] = $("#endSinglePutTime").val();//生产日期截止
        table.reload(StorageStock.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    
    // 导入excel
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: 'Inventory Import',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/storageStock/toimportExcel',
            end: function () {
                table.reload(StorageStock.tableId);
            }
        });
    });

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + StorageStock.tableId,
        url: Feng.ctxPath + '/storageStock/stockList',
        page: true,
        limit: 120,
		limits:[60,120,240,360,480,1500,5000,10000,20000,80000],
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        totalRow: true ,//开启合计行
        cols: StorageStock.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
    	StorageStock.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        var checkRows = table.checkStatus(StorageStock.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    });

    // 导出excel
    $('#btnExpBySpec').click(function () {
		window.location.href = Feng.ctxPath + '/storageStock/exportExcelBySpec?stockstate='+$("#stockstate").val()
		+"&operateId="+$("#operateId").val()+"&customerId="+$("#customerId").val()
		+"&warehouseId="+$("#warehouseId").val()+"&areaId="+$("#areaId").val()+"&positionNumber="+$("#positionNumber").val()
		+"&goodsNumber="+$("#goodsNumber").val()+"&goodsName="+$("#goodsName").val()+"&goodsNo="+$("#goodsNo").val()
		+"&startPutTime="+$("#startPutTime").val()+"&endPutTime="+$("#endPutTime").val()
		+"&goodsbatchs="+$("#goodsbatchs").val()
		+"&startSingleTime="+$("#startSingleTime").val()+"&endSinglePutTime="+$("#endSinglePutTime").val();
    });

    // 添加按钮点击事件
    $('#add').click(function () {
        window.location.href = Feng.ctxPath + '/storageStock/add';
    });

    // 工具条点击事件
    table.on('tool(' + StorageStock.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

		if (layEvent === 'todetailed') {
		    layer.open({
		        type: 2,
		        title: 'Transaction Details',
		        area: ['1200px', '600px'],
		        anim: 5,
		        content: Feng.ctxPath + '/storageStockDetailed?stockId=' + data.id,
	            end: function () {
	            }
		    });
        }
    });

    // 单击行事件
    table.on('row(' + StorageStock.tableId + ')', function (obj) {
		$('div[lay-id="' + StorageStock.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//Restore other rows to original style
		$('div[lay-id="' + StorageStock.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6;" });//Change current row color
    });
	    
	//批量删除
    $('#btnRevoke').click(function () {
    	var checkStatus = table.checkStatus('storageStockTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/storageStock/btnRevoke?ids="+ids, function (data) {
	                if(data.success){
	                	Feng.success("Delete successful!");
	                	table.reload(StorageStock.tableId);
	                } else {
	                    Feng.error("Delete failed!" + data.message + "!");
	                }
                }, function (data) {
                    Feng.error("Delete failed!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Are you sure to delete selected records?", operation);
		} else {
			layer.alert('Please select at least one record');
		}
    });

    //点击选择库位
    $('#choicep').click(function () {
        layer.open({
            type: 2,
            title: 'Select Location',
            area: ['900px', '500px'],
            content: Feng.ctxPath + '/storagePutSingle/toPositionStock?positionAreaId='+$("#areaId").val()+'&warehouseId='+$("#warehouseId").val(),
            end: function () {
                $("#positionNumber").val(StoragePutSingleInfoDlg.data.positionNumber);//Location number
            }
        });
    });
    
    //点击选择商品名称
    $('#choiceg').click(function () {
    	var customerId = $("#customerId").val();
    	if (customerId==null||customerId=='') {
    		layer.msg('Please select customer'); 
		} else {
	        layer.open({
	            type: 2,
	            title: 'Select Product',
	            area: ['900px', '500px'],
	            content: Feng.ctxPath + '/orderPutDetailed/toChoiceGoods?goodsCustomerId=' + customerId,
	            end: function () {
	                $("#goodsNumber").val(OrderPutDetailedInfoDlg.data.goodsNumber);//Product number
	                $("#goodsName").val(OrderPutDetailedInfoDlg.data.detailedGoodsname);//Product name
	                $("#goodsNo").val(OrderPutDetailedInfoDlg.data.goodsNo);//SKU
	            }
	        });
		}
    });
    
    //查询库区
    form.on('select(warehouseId)',function(){
    	$("#areaId").empty();
    	$.ajax({
    		url:Feng.ctxPath + '/basicArea/Querylist',
    	    dataType:"json",   //返回格式为json
    	    async: false,
    	    data:{"areaWarehouseId":$("#warehouseId").val()},    //参数值
    	    type:"post",   //请求方式
    	    success:function(data){
    	        if(data.length>0){
    	        	var str = "<option value=''>Select Area</option>";
    	        	$.each(data,function(key,value){
    	        		str += "<option value='"+value.id+"'>"+value.areaName+"</option>";
    	        	});
    	        	$("#areaId").html(str);
    	        }
    	    }
    	});
        form.render('select');
    });

});
